﻿#ifndef WEATHERTOW_H
#define WEATHERTOW_H
#include<QMap>
#include<QFile>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonValue>
class WeatherTool{
private:
    static QMap<QString,QString>mCityMap;
    static void initCityMap(){
        // 读取文件
        QFile file(":/citycode.json");
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            // 处理文件打开失败的情况
            return;
        }
        QByteArray json = file.readAll();
        file.close();
        // 解析json，并且写入到map，这个文件是json数组
        QJsonParseError error;
        QJsonDocument doc = QJsonDocument::fromJson(json, &error);
        if (error.error != QJsonParseError::NoError || !doc.isArray())
        {
            // 处理JSON解析失败的情况
            return;
        }
        QJsonArray cities=doc.array();
        for(int i=0;i<cities.size();i++){
           QString city= cities[i].toObject().value("city_name").toString();
           QString code= cities[i].toObject().value("city_code").toString();
           if(code.size()>0){
               mCityMap.insert(city,code);
           }

        }
    }
 public:
    static QString getCityCode(QString cityName){
        if(mCityMap.isEmpty()){
            initCityMap();
        }
        QMap<QString,QString>::iterator it= mCityMap.find(cityName);
        if (it == mCityMap.end())
        {
            it = mCityMap.find(cityName + "市");
        }
        if (it == mCityMap.end())
        {
            it = mCityMap.find(cityName + "区");
        }
        if (it == mCityMap.end())
        {
            it = mCityMap.find(cityName + "县");
        }
        if (it != mCityMap.end())
        {
            return it.value();
        }
        return ""; // 没有就返回空
    }
};
QMap<QString,QString>WeatherTool::mCityMap={};

#endif // WEATHERTOW_H
